package com.cookor.poi.modules.phy.service;

import com.cookor.poi.common.persistence.DataEntity;
import com.cookor.poi.common.persistence.Page;
import com.cookor.poi.common.service.CrudService;
import com.cookor.poi.modules.phy.dao.TForkDao;
import com.cookor.poi.modules.phy.entity.TDoctor;
import com.cookor.poi.modules.phy.entity.TFork;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(readOnly = true)
public class TForkService extends CrudService<TForkDao, TFork> {
  @Autowired
  @Lazy
  private TDoctorService tDoctorService;
  
  public TFork get(String id) {
    return (TFork)super.get(id);
  }
  
  public List<TFork> findList(TFork tFork) {
    return super.findList( tFork);
  }
  
  public Page<TFork> findPage(Page<TFork> page, TFork tFork) {
    return super.findPage(page,  tFork);
  }
  
  @Transactional(readOnly = false)
  public void save(TFork tFork) {
    super.save( tFork);
  }
  
  @Transactional(readOnly = false)
  public void delete(TFork tFork) {
    super.delete( tFork);
  }
  
  public TFork findByParam(String openId, Integer doctorId) {
    return ((TForkDao)this.dao).findByParam(openId, doctorId);
  }
  
  @Transactional(readOnly = false, rollbackFor = {Exception.class})
  public void addFork(String openId, Integer doctorId, Integer status) throws Exception {
    synchronized (doctorId) {
      TFork fork = findByParam(openId, doctorId);
      if (fork == null) {
        fork = new TFork();
        fork.setDoctorId(doctorId);
        fork.setOpenId(openId);
        fork.setStatus(status);
      } else {
        if (fork.getStatus() == status)
          return; 
        fork.setStatus(status);
      } 
      save(fork);
      TDoctor tDoctor = this.tDoctorService.get(doctorId.toString());
      int i = (status.intValue() == 1) ? 1 : -1;
      tDoctor.setFollow(Integer.valueOf(tDoctor.getFollow().intValue() + i));
      this.tDoctorService.save(tDoctor);
    } 
  }
}
